<template>
  <div>
    <el-row class="step">
      <el-col :span="24">
        <el-steps :active="num" align-center finish-status="success">
          <el-step title="身份认证" description="请先完成身份认证" />
          <el-step title="支付订单" description="请支付订单" />
          <el-step title="完成支付" description="支付成功" />
        </el-steps>
      </el-col>
    </el-row>
    <el-row class="zujian" v-if="show === 1">
      <el-col :span="24">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idcard">
            <el-input
              v-model="ruleForm.idcard"
              type="text"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model.number="ruleForm.phonenumber" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)"
              >提交信息</el-button
            >
            <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row class="zujian" v-if="show === 2">
      <el-col :span="24">
        <el-row>
          <el-col :span="24">
            <h2>订单信息</h2>
            <p>预订房源住房时间：{{ renttime }}</p>
            <p>预订人数：{{ peoplenum }}</p>
            <p>支付价格：￥{{ total }}</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" plain @click="open">立即支付</el-button>
            <el-button type="success" plain @click="backhome"
              >回到首页</el-button
            >
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row class="zujian" v-if="show === 3">
      <el-col :span="24">
        <el-icon style="font-size=27px;color:green"><SuccessFilled /></el-icon>
        <span>支付成功</span>
      </el-col>
      <el-row :gutter="20" style="margin-top: 30px">
        <el-col :span="12">
          <el-button type="danger" round @click="lookorder">查看订单</el-button>
        </el-col>
        <el-col :span="12">
          <el-button type="info" round @click="backhome">去首页</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top: 70px" v-if='lookorderisshow'>
        <el-col :span="24">
          <p>您的订单信息</p>
          <p>住房日期：{{renttime}}</p>
          <p>订购人姓名：{{ruleForm.name}}</p>
          <p>预留电话：{{ruleForm.phonenumber}}</p>
          <p style="color:red">关于退订：{{isfree}}</p>
          <p>房源地点：{{place}}</p>
          <p>房源描述：{{miaosu}}</p>
          <p>房源类型：{{housetype}}</p>
        </el-col>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { ref, reactive, getCurrentInstance, onMounted, toRefs } from "vue";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
// 引入二维码
import QRCode from "qrcode";
let { proxy } = getCurrentInstance();
let route = useRoute();
let router = useRouter();
// console.log(route.query);
let { renttime, peoplenum, token, hid, total } = route.query;
let show = ref(1);
let num = ref(0);
const ruleFormRef = ref();
let timer = null;
let paycode = "";
let lookorderisshow=ref(false);
let houseinformation=reactive({
  miaosu:'',
  place:'',
  housetype:'',
  isfree:''
});
let {miaosu,place,housetype,isfree} =toRefs(houseinformation)
const checkphonenumber = (rule, value, callback) => {
  let phonenumberReg =
    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  if (!value) {
    callback(new Error("请输入手机号"));
  } else if (!phonenumberReg.test(value)) {
    callback(new Error("请输入正确格式的手机号"));
  } else {
    callback();
  }
};

const validatename = (rule, value, callback) => {
  let nameReg = /^([\u4e00-\u9fa5]{1,20}|[a-zA-Z\.\s]{1,20})$/;
  if (value === "") {
    callback(new Error("请输入真实姓名不能不填"));
  } else if (!nameReg.test(value)) {
    callback(
      new Error(
        "请输入正确的姓名，要求不能有特殊字符和数字以及中文英文不能同时出现"
      )
    );
  } else {
    callback();
  }
};
const validateidcard = (rule, value, callback) => {
  let idcardReg =
    /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  if (value === "") {
    callback(new Error("请输入身份证号不能不填"));
  } else if (!idcardReg.test(value)) {
    callback(new Error("请输入正确格式的身份证号"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  name: "",
  idcard: "",
  phonenumber: "",
});

const rules = reactive({
  name: [{ validator: validatename, trigger: "blur" }],
  idcard: [{ validator: validateidcard, trigger: "blur" }],
  phonenumber: [{ validator: checkphonenumber, trigger: "blur" }],
});

let oid = undefined;
const submitForm = (formEl) => {
  if (!formEl) return;
  console.log(ruleForm);
  formEl.validate(async (valid) => {
    if (valid) {
      // console.log('submit!');
      let obj = {
        renttime,
        peoplenum,
        token: "",
        hid,
        tenantname: ruleForm.name,
        tenantidnumber: ruleForm.idcard,
        tenantphonenumber: ruleForm.phonenumber,
      };
      let res = await proxy.$axios("/houseorsersubmit", { params: obj });
      // console.log(res);
      if (res.data.info == "success") {
        num.value = 1;
        show.value = 2;
        oid = res.data.data[0];
      }
    } else {
      // console.log('error submit!')
      ElMessage.error("填写信息有误，提交失败");
      return false;
    }
  });
};

const open = async () => {
  // 生成二维码
  let url = await QRCode.toDataURL("https://mp.weixin.qq.com/cgi-bin/wx");
  ElMessageBox.alert(`<img src="${url}" />`, "请支付", {
    dangerouslyUseHTMLString: true,
    center: true,
    showCancelButton: true,
    confirmButtonText: "已支付成功",
    cancelButtonText: "支付遇见问题",
    showClose: false,
    // 关闭弹出框配置
    beforeClose: (type, instance, done) => {
      // type区分取消还是确定按钮，instance当前组件实例，done关闭弹窗方法
      if (type == "cancel") {
        ElMessage({
          message: "请联系管理员",
          type: "success",
        });
        clearInterval(timer);
        timer = null;
        done();
      } else if (type == "confirm") {
        if (!timer) {
          timer = setInterval(() => {
            if (paycode == 2009) {
              clearInterval(timer);
              timer = null;
              done();
              num.value = 3;
              show.value = 3;
            }
          }, 7000);
        }
      }
    },
  });
  // console.log(oid);
  // 发请求获取用户支付状态
  let result = await proxy.$axios("/orderpay", { params: oid });
  if (result.data.code == 2009) {
    paycode = result.data.code;
  }
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 回到更多房源
// 回到首页
let backhome = () => {
  // router.push('/home');
  lookorderisshow.value=false;
};
let tuimiaoshu=undefined;
let lookorder=async ()=>{
  lookorderisshow.value=true;
  let res=await proxy.$axios(`/viewingOrderInformation?hid=${hid}`);
  console.log(res);
  tuimiaoshu=res.data[0].isfree;
  if(tuimiaoshu==1){
    isfree.value='您可以在入住前48小时免费退订';
  }else if(tuimiaoshu==0){
    isfree.value='您不可以在入住前48小时免费退订，需要收取10%的每晚预订费用'
  }
  miaosu.value=res.data[0].miaosu;
  place.value=res.data[0].place;
  housetype.value=res.data[0].housetype;
}
</script>

<style lang='scss' scoped>
.step {
  margin-top: 20px;
}
.zujian {
  width: 80%;
  margin: 50px auto;
}
</style>